from multiprocessing import Process,Barrier
from multiprocessing.shared_memory import SharedMemory
import struct
import time
import datetime

class main_process(Process):
    def __init__(self, shm_name,barrier,warmup_cycles,duration):
        super(main_process, self).__init__()
        self.shm_name = shm_name
        self.barrier = barrier
        self.warmup_cycles=warmup_cycles
        self.duration=duration


    def worker(self):
        current_time = time.time()
        # 预热阶段（解决系统时间API初始延迟问题）
        for i in range(self.warmup_cycles):
            target_time = current_time + self.duration
            while time.time() < target_time:
                pass  # 忙等待
            current_time = target_time
            print(f"主程序: 预热完成 {i + 1}/{self.warmup_cycles}")
        # 等待所有线程完成预热
        self.barrier.wait()
    def run(self):
        shm = SharedMemory(name=self.shm_name)
        self.barrier.wait()
        start_time = int(time.time())
        while True:
            cycle_number = int((time.time() - start_time) / self.duration) + 1
            target_time = start_time + cycle_number * self.duration

            shm.buf[:8] = struct.pack('q', target_time)
            while time.time() < target_time - 0.001:  # 提前1ms结束忙等待
                time.sleep(max(0, (target_time - time.time()) * 0.5))  # 动态调整等待
            while time.time() < target_time:
                time.sleep(max(0, (target_time - time.time()) * 0.5))  # 空转等待，确保精准
            actual_time = time.time()
            latency = actual_time - target_time
            print(f"主线程: {datetime.datetime.now()} | "
                  f"目标: {target_time} | 实际: {actual_time:.6f} | "
                  f"延迟: {latency * 1000:.3f}ms")
class son_process(Process):
    def __init__(self, shm_name,barrier,warmup_cycles,duration,process_name):
        super(son_process, self).__init__()
        self.shm_name = shm_name
        self.barrier = barrier
        self.warmup_cycles=warmup_cycles
        self.duration=duration
        self.process_name=process_name
    def worker(self):
        current_time = time.time()
        # 预热阶段（解决系统时间API初始延迟问题）
        for i in range(self.warmup_cycles):
            target_time = current_time + self.duration
            while time.time() < target_time:
                pass  # 忙等待
            current_time = target_time
            print(f"子程序{self.process_name}: 预热完成 {i + 1}/{self.warmup_cycles}")
        # 等待所有线程完成预热
        self.barrier.wait()
    def run(self):
        shm=SharedMemory(name=self.shm_name)
        self.barrier.wait()
        while True:
            target_time, = struct.unpack('q',shm.buf[:8])
            while target_time==0:
                time.sleep(0.01)
                target_time, = struct.unpack('q', shm.buf[:8])
            while time.time() < target_time - 0.001:  # 提前1ms结束忙等待
                time.sleep(max(0, (target_time - time.time()) * 0.5))  # 动态调整等待
            while time.time() < target_time:
                time.sleep(max(0, (target_time - time.time()) * 0.5))  # 空转等待，确保精准
            actual_time = time.time()
            latency = actual_time - target_time
            print(f"子程序{self.process_name}: {datetime.datetime.now()} | "
                  f"目标: {target_time} | 实际: {actual_time:.6f} | "
                  f"延迟: {latency * 1000:.3f}ms")




if __name__ == '__main__':
    processes = []
    barrier = Barrier(4)
    # 创建共享内存，存储一个双精度浮点数（8字节）
    shm = SharedMemory(create=True, size=8)
    shm.buf[:8] = struct.pack('q', 0)
    warmup_cycles=3
    duration=2
    # 写入初始值 3.14
    processes.append(main_process(shm.name,barrier,warmup_cycles,duration))
    for i in range(3):
        process=son_process(shm.name,barrier,warmup_cycles,duration,i)
        processes.append(process)
    for p in processes:
        p.start()

